package org.simple.framework.boot.controller;

import org.simple.framework.boot.controller.extra.BaseModelJpaQueryController;
import org.simple.framework.data.entity.Identifiable;
import org.simple.framework.data.jpa.query.JpaQuerySpecification;
import org.simple.framework.data.query.BaseQuery;
import org.simple.framework.web.result.exception.web.NotImplementedException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.security.Principal;
import java.util.List;

/**
 * 项目名称：simple-framework
 * 类名称：ModelJpaQueryController
 * 类描述：ModelJpaQueryController
 * 创建时间：2018/9/7
 * <p>
 * 原来Q有限制BaseQuery,但是GenericTypeResolver抓泛型类型的时候 抓到的是父类类型
 * 把接口改成抽象类又能抓到实现类类型
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 * @see BaseModelJpaQueryController 抽象类版本
 */
public interface ModelJpaQueryController<E extends Identifiable<ID>, ID extends Serializable, Q> extends ModelController<E, ID> {

    void handleQuery(Q query, Principal principal);

    @PostMapping("/query")
    default List<E> query(@RequestBody Q query, Principal principal) {
        handleQuery(query, principal);
        if (!(query instanceof BaseQuery)) {
            throw new NotImplementedException("Q must extends BaseQuery");
        }
        return getRepository().findAll(new JpaQuerySpecification<>((BaseQuery) query));
    }

    @PostMapping("/query/page")
    default Page<E> queryByPage(@RequestBody Q query, Pageable pageable, Principal principal) {
        handleQuery(query, principal);
        if (!(query instanceof BaseQuery)) {
            throw new NotImplementedException("Q must extend BaseQuery");
        }
        return getRepository().findAll(new JpaQuerySpecification<>((BaseQuery) query), pageable);
    }

}
